package com.wwwarehouse.carddesk.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.activity.CardDeskActivity;
import com.wwwarehouse.carddesk.common.CardDeskCommon;
import com.wwwarehouse.carddesk.constant.CardDeskConstant;
import com.wwwarehouse.carddesk.eventbus_event.CardDeskTaskFilterEvent;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.adapter.carddesk.MyFragmentPagerAdapter;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.SlideBarView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.fragment.DeskDrawerMultipleFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;

@Route(path = "/carddesk/TaskTabFragment")
public class TaskTabFragment extends BaseFragment {
    private View mRootView;

    private LinearLayout mResultLayout;
    private LinearLayout mEmptyLayout;
    private ImageView mEmptyImg;
    private TextView mEmptyTxt;

    private StateLayout mStateLayout;
    private ElasticScrollView mElasticScrollView;
    private CustomViewPagerInternal mCustomViewPagerInternal;
    private CirclePageIndicator mCirclePageIndicator;
    private SlideBarView mSlideBarView;
    private List<Fragment> mFragmentList;

    private String mOrderSort;
    private String mOrderType;
    private String mSearchText;
    private Set<String> mTaskTagSet;

    private List<FilterBean> mFilterList;

    private List<CardDeskTaskResponseBean.TaskTagBean> mTaskTagList;

    //用于第一次切换的标记位
    private boolean mIsFirstEnterTask = false;

    private static final int REQUEST_GET_TASK_INFO = 0;

    public static final int LIMIT = 9;
    public static final int PAGE = 1;

    public static final String KEY_TASK_ORDER_SORT = "key_task_order_sort";
    public static final String KEY_TASK_ORDER_TYPE = "key_task_order_type";
    public static final String KEY_TASK_SEARCH_TEXT = "key_task_search_text";
    public static final String KEY_TASK_TAG_SET = "key_task_tag_set";
    public static final String KEY_TASK_PAGE = "key_task_page";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_task_tab, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
        initEvent();
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }

    private void initView() {
        mResultLayout = findView(mRootView, R.id.ll_result);
        mEmptyLayout = findView(mRootView, R.id.ll_empty);
        mEmptyImg = findView(mRootView, R.id.iv_empty);
        mEmptyTxt = findView(mRootView, R.id.tv_empty);

        mStateLayout = findView(mRootView, R.id.sl_layout);

        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mStateLayout.getProgressviewLayoutparam();
        params.bottomMargin += ConvertUtils.dip2px(mActivity, 19);
        mStateLayout.showProgressView(false);

        mElasticScrollView = findView(mRootView, R.id.esv_elastic);
        mCustomViewPagerInternal = findView(mRootView, R.id.vpi_invite);
        mCirclePageIndicator = findView(mRootView, R.id.cpi_indicator);
        mSlideBarView = findView(mRootView, R.id.sbv_slide);

        mFragmentList = new ArrayList<>();

        mOrderSort = "";
        mOrderType = "";
        mSearchText = "";
        mTaskTagSet = new HashSet<>();

        mFilterList = new ArrayList<>();
    }

    private void initData() {
        getTaskInfo();
    }

    private void initEvent() {
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                // 隐藏搜索页面的业务单位按钮
                ((BaseCardDeskActivity) mActivity).hideFunctionUnitText();
                ((BaseCardDeskActivity) mActivity).downPull_4();
            }

            @Override
            public void onUpPull() {

            }
        });
    }

    @Override
    public void setTitle() {

    }

    @Override
    public void requestDatas() {

    }

    public String getOrderSort() {
        return mOrderSort;
    }

    public void setOrderSort(String orderSort) {
        this.mOrderSort = orderSort;
    }

    public String getOrderType() {
        return mOrderType;
    }

    public void setOrderType(String orderType) {
        this.mOrderType = orderType;
    }

    public String getSearchText() {
        return mSearchText;
    }

    public void setSearchText(String searchText) {
        this.mSearchText = searchText;
    }

    public Set<String> getTaskTagSet() {
        return mTaskTagSet;
    }

    public void setTaskTagSet(Set<String> taskTagSet) {
        this.mTaskTagSet = taskTagSet;
    }

    public List<CardDeskTaskResponseBean.TaskTagBean> getTaskTagList() {
        return mTaskTagList;
    }

    public void setTaskTagList(List<CardDeskTaskResponseBean.TaskTagBean> taskTagList) {
        this.mTaskTagList = taskTagList;
    }

    public void getTaskInfo(boolean... isSearch) {
        if (isSearch.length > 0 && isSearch[0]) {
            mStateLayout.showProgressView(false);
        }

        Map map = new HashMap<>();

        map.put("limit", LIMIT);
        map.put("page", PAGE);
        map.put("orderSort", mOrderSort);
        map.put("orderType", mOrderType);
        map.put("searchText", mSearchText);
        map.put("taskTags", mTaskTagSet);

        NoHttpUtils.httpPost(CardDeskConstant.URL_GET_TASK_INFO, map, mOnResponseListener, REQUEST_GET_TASK_INFO);
    }

    public void initDrawerLayout() {
        DeskDrawerMultipleFragment deskDrawerMultipleFragment = DeskDrawerMultipleFragment.newInstance(getString(R.string.task_category), mFilterList, 2);
        ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_GET_TASK_INFO:
                    if ("0".equals(commonClass.getCode())) {
                        CardDeskTaskResponseBean cardDeskTaskResponseBean = JSON.parseObject(commonClass.getData().toString(), CardDeskTaskResponseBean.class);
                        mOrderSort = cardDeskTaskResponseBean.getOrderSort();
                        mOrderType = cardDeskTaskResponseBean.getOrderType();
                        mTaskTagList  = cardDeskTaskResponseBean.getTaskTags();

                        if ("ASC".equals(mOrderSort) && "emergency_degree".equals(mOrderType)) {
                            EventBus.getDefault().post(new CardDeskTaskFilterEvent(2));
                        } else {
                            EventBus.getDefault().post(new CardDeskTaskFilterEvent(3));
                        }

                        if (mTaskTagList != null) {
                            //有筛选条件
                            if (mTaskTagSet.size() > 0) {
                                for (String taskTagValue : mTaskTagSet) {
                                    for (CardDeskTaskResponseBean.TaskTagBean taskTagBean : mTaskTagList) {
                                        if (taskTagValue.equals(taskTagBean.getTagValue())) {
                                            for (FilterBean filterBean : mFilterList) {
                                                if (taskTagBean.getTagRemark().equals(filterBean.getText())) {
                                                    filterBean.setSelect(true);
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                //初始化抽屉数据
                                mFilterList.clear();

                                for (CardDeskTaskResponseBean.TaskTagBean taskTagBean : mTaskTagList) {
                                    mFilterList.add(new FilterBean(false, taskTagBean.getTagRemark()));  //全部未选
                                }
                            }
                        }

                        initDrawerLayout();

                        // 总共多少页
                        int total = cardDeskTaskResponseBean.getTotal();
                        if (total == 0) {
                            if (TextUtils.isEmpty(mSearchText)) {
                                //没有请求数据
                                mResultLayout.setVisibility(View.VISIBLE);
                                mEmptyLayout.setVisibility(View.GONE);

                                mStateLayout.showEmptyView(false);
                                mStateLayout.setEmptyListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        mStateLayout.showProgressView(false);

                                        getTaskInfo();
                                    }
                                });
                            } else {
                                //没有搜索结果
                                mResultLayout.setVisibility(View.GONE);
                                mEmptyLayout.setVisibility(View.VISIBLE);

                                mEmptyImg.setImageResource(R.drawable.search_empty);
                                mEmptyTxt.setText(R.string.invite_search_no_result);
                            }

                            //第一次进来，没有任务列表，直接跳转到功能列表
                            if (!mIsFirstEnterTask) {
                                ((CardDeskActivity) mActivity).switchFunctionTab();
                            }
                        } else {
                            mResultLayout.setVisibility(View.VISIBLE);
                            mEmptyLayout.setVisibility(View.GONE);

                            //结果不为空，并且数据没有变化，不刷新界面
                            if (commonClass.getData().toString().equals(CardDeskCommon.getInstance().getTaskLastResult())) {
                                return;
                            }

                            //保存请求结果
                            CardDeskCommon.getInstance().setTaskLastResult(commonClass.getData().toString());

                            int page = (total % 9 == 0) ? total / 9 : (total / 9 + 1);

                            mFragmentList.clear();

                            for (int i = 0; i < page; i++) {
                                TaskDetailsFragment taskDetailsFragment = new TaskDetailsFragment();
                                Bundle bundle = new Bundle();
                                bundle.putString(KEY_TASK_ORDER_SORT, mOrderSort);
                                bundle.putString(KEY_TASK_ORDER_TYPE, mOrderType);
                                bundle.putString(KEY_TASK_SEARCH_TEXT, mSearchText);
                                bundle.putSerializable(KEY_TASK_TAG_SET, (Serializable) mTaskTagSet);
                                bundle.putInt(KEY_TASK_PAGE, (i + 1));
                                taskDetailsFragment.setArguments(bundle);

                                mFragmentList.add(taskDetailsFragment);
                            }

                            /**
                             * 需要管理相互独立的并且隶属于Activity的Fragment使用FragmentManager()，
                             * 而在Fragment中动态的添加Fragment要使用getChildFragmentManager()来管理。
                             */
                            mCustomViewPagerInternal.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), mFragmentList));

                            if (page <= 6) {
                                if (page > 1) {
                                    mCirclePageIndicator.setVisibility(View.VISIBLE);
                                    mSlideBarView.setVisibility(View.GONE);

                                    mCirclePageIndicator.setViewPager(mCustomViewPagerInternal, 0);
                                } else {
                                    mCirclePageIndicator.setVisibility(View.GONE);
                                    mSlideBarView.setVisibility(View.GONE);
                                }
                            } else {
                                mCirclePageIndicator.setVisibility(View.GONE);
                                mSlideBarView.setVisibility(View.VISIBLE);

                                mSlideBarView.setTotalPage(page);
                                mSlideBarView.setOnSlideChange(new SlideBarView.OnSlideChange() {
                                    @Override
                                    public void onSlideChange(int page) {
                                        mCustomViewPagerInternal.setCurrentItem(page, false);
                                    }
                                });

                                mSlideBarView.setViewPagerInternal(mCustomViewPagerInternal);
                            }
                        }

                        mIsFirstEnterTask = true;
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), false);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mStateLayout.showProgressView(false);

                                getTaskInfo();
                            }
                        });
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            mStateLayout.showNetworkView(false);
            mStateLayout.setNetworkListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mStateLayout.showProgressView(false);

                    getTaskInfo();
                }
            });
        }

        @Override
        public void onFinish(int what) {
            mStateLayout.showContentView();
        }
    };
}
